package com.tlw.practice.tlw.controller;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.tlw.practice.tlw.common.CommonResult;
import com.tlw.practice.tlw.common.ResultCode;
import com.tlw.practice.tlw.pojo.dto.UserDto;
import com.tlw.practice.tlw.pojo.form.UserLoginForm;
import com.tlw.practice.tlw.service.UserService;
import com.tlw.practice.tlw.utils.JWTUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@Api(tags = "用户管理")
@RequestMapping("/user")
@RestController
public class UserController {
    @Autowired
    private UserService userService;


    @ApiOperation("查询全部用户")
    @GetMapping("/findall")
    public CommonResult findAll(){
//        return CommonResult.success(userService.findAll());
        return CommonResult.success();
    }

    @ApiOperation("登陆")
    @PostMapping("/login")
    public CommonResult login(@RequestBody UserLoginForm userLoginForm){
        String token = userService.login(userLoginForm.getUsername(), userLoginForm.getPassword());

        return token != null ? CommonResult.success(token) : CommonResult.error(ResultCode.LOGON_FAILURE);
    }
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public CommonResult getUserInfo(HttpServletRequest request){
        // 经过拦截器拦截，到这的都是可用的token， 从请求头获取token
        String token = request.getHeader("X-Token");
        String username = JWTUtils.getUserNameFromToken(token);
        UserDto userInfo = userService.getUserInfoByUsername(username);
        return CommonResult.success(userInfo);
    }

}


